package com.zhizuobiao.coura.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.zhizuobiao.coura.adapter.HKStockListAdapter;
import com.zhizuobiao.coura.application.MyApplication;
import com.zhizuobiao.coura.stock.HKStockList;
import com.zhizuobiao.coura.stock.HKStockService;
import com.zhizuobiao.coura.stockhelper.R;
import com.zhizuobiao.coura.stockhelper.StockActivity;
import com.zhizuobiao.coura.view.XListView;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by coura on 2016/12/13.
 */

public class HKSFragment extends Fragment implements XListView.IXListViewListener {

    @BindView(R.id.lv_hks)
    XListView lvHks;
    private View view;
    private MyApplication myApplication;
    private HKStockService hkStockService;
    private HKStockList hkStock;
    private HKStockListAdapter hkStockListAdapter;
    private List<HKStockList.ResultBean.DataBean> list;
    private Handler mHandler;
    private int page = 1;
    private static final String APPKEY = "81b0a782ae1a008d322f47bbb5907458";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_hks, null);
        ButterKnife.bind(this, view);
        getActivity().findViewById(R.id.tv_Chg);
        init();
        return view;
    }

    private void init() {
        myApplication = (MyApplication) getActivity().getApplication();
        hkStockService = myApplication.getHkStockService();
        loadDate("1",APPKEY);
        lvHks.setPullLoadEnable(true);
        lvHks.setXListViewListener(this);
        mHandler = new Handler();
        lvHks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String gid = list.get(position-1).getSymbol();
                Intent intent = new Intent(getActivity(),StockActivity.class);
                intent.putExtra("num",0);
                intent.putExtra("gid",gid);
                startActivity(intent);
            }
        });
    }

    /**
     * 加载网络股票信息
     * @param page
     * @param key
     */
    private void loadDate(String page,String key){
        this.page = 1;
        Call<HKStockList> hkStockCall = hkStockService.getStockList(page,key);
        hkStockCall.enqueue(new Callback<HKStockList>() {
            @Override
            public void onResponse(Call<HKStockList> call, Response<HKStockList> response) {
                hkStock = response.body();
                if (hkStock.getError_code() == 0){
                    list = hkStock.getResult().getData();
                    hkStockListAdapter = new HKStockListAdapter(getActivity(),list);
                    lvHks.setAdapter(hkStockListAdapter);
                }
            }
            @Override
            public void onFailure(Call<HKStockList> call, Throwable t) {
                Toast.makeText(getActivity(),"数据加载出错，请查看网络是否连接",Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 下拉加载更多数据
     * @param page
     * @param key
     */
    private void loadMoreDate(String page,String key){
        Call<HKStockList> hkStockCall = hkStockService.getStockList(page,key);
        hkStockCall.enqueue(new Callback<HKStockList>() {
            @Override
            public void onResponse(Call<HKStockList> call, Response<HKStockList> response) {
                hkStock = response.body();
                if (hkStock!=null){
                    List<HKStockList.ResultBean.DataBean> list1 = hkStock.getResult().getData();
                    list.addAll(list1);
                    hkStockListAdapter = new HKStockListAdapter(getActivity(),list);
                    lvHks.setAdapter(hkStockListAdapter);
                }
            }
            @Override
            public void onFailure(Call<HKStockList> call, Throwable t) {

            }
        });
    }

    /**
     * list中的涨跌幅从小到大排序
     * 重新配置listview的适配器
     */
    public void resetAdapter1(){
        sort1();
        hkStockListAdapter = new HKStockListAdapter(getActivity(),list);
        lvHks.setAdapter(hkStockListAdapter);
    }

    /**
     * list中的涨跌幅从大到小排序
     * 重新配置listview的适配器
     */
    public void resetAdapter2(){
        sort2();
        hkStockListAdapter = new HKStockListAdapter(getActivity(),list);
        lvHks.setAdapter(hkStockListAdapter);
    }

    /**
     * list中的涨跌幅从小到大排序
     */
    private void sort1(){
        Collections.sort(list, new Comparator<HKStockList.ResultBean.DataBean>() {
            @Override
            public int compare(HKStockList.ResultBean.DataBean lhs, HKStockList.ResultBean.DataBean rhs) {
                if(Double.parseDouble(lhs.getChangepercent())>Double.parseDouble(rhs.getChangepercent())){
                    return 1;
                }
                return -1;
            }
        });
    }

    /**
     * list中的涨跌幅从大到小排序
     */
    private void sort2(){
        Collections.sort(list, new Comparator<HKStockList.ResultBean.DataBean>() {
            @Override
            public int compare(HKStockList.ResultBean.DataBean lhs, HKStockList.ResultBean.DataBean rhs) {
                if(Double.parseDouble(lhs.getChangepercent())<Double.parseDouble(rhs.getChangepercent())){
                    return 1;
                }
                return -1;
            }
        });
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadDate("1",APPKEY);
                lvHks.stopRefresh();
                lvHks.stopLoadMore();
            }
        },2000);
    }

    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                loadMoreDate(page+"",APPKEY);
                lvHks.stopRefresh();
                lvHks.stopLoadMore();
            }
        },2000);
    }
}
